import classNames from 'classnames';
import { useMutation } from '@tanstack/react-query';
import type { TBody } from '@/types';
import { postView } from '@/services/api';
import type { IPost, IPostBadge } from '@/interfaces';
import Link from 'next/link';
import PostReviewHistory from '@/app/[locale]/common/post/reviewHistory';

export default function PostName({
  item,
  isEdit,
  isTable,
  isJustifyContentCenter,
  isFwSemibold = true,
  boxClassName,
  textDecorationNone,
  isPostReviewHistory,
}: {
  item: IPost;
  isEdit?: boolean;
  isTable?: boolean;
  isJustifyContentCenter?: boolean;
  isFwSemibold?: boolean;
  boxClassName?: string;
  textDecorationNone?: boolean;
  isPostReviewHistory?: boolean;
}) {
  const { id, name, badges, styles, contentType, contentLink } = item;
  const style = styles.find((value) => value.type === 'NAME');
  const isLink = contentType === 'LINK' && !!contentLink;
  let _icons: string[] = [];
  let _classes: string[] = [];
  let _styles = {};

  if (style) {
    _icons = style.icons;

    if (style.useClass && style.classes && style.classes.length > 0) {
      _classes = style.classes;
    }

    if (
      style.useStyle &&
      style.styles &&
      Object.keys(style.styles).length > 0
    ) {
      _styles = style.styles;
    }
  }

  return (
    <div
      className={classNames(
        'd-flex align-items-center flex-wrap gap-2',
        {
          'fs-5': !isTable,
          'justify-content-center': isJustifyContentCenter,
          'fw-semibold': isFwSemibold,
        },
        boxClassName,
      )}
    >
      <Style icons={_icons} styles={_styles} classes={_classes} />

      <Badges items={badges} />

      <Name
        id={id}
        name={name}
        classes={_classes}
        styles={_styles}
        isEdit={isEdit}
        isLink={isLink}
        contentLink={contentLink}
        textDecorationNone={textDecorationNone}
      />

      {isPostReviewHistory && <PostReviewHistory item={item} />}
    </div>
  );
}

const Badges = ({ items }: { items: IPostBadge[] }) => {
  return (
    <>
      {items
        .sort((a, b) => a.sort - b.sort)
        .map((item) => {
          const style: any = {};
          if (item.colorMode !== 'DEFAULT' && item.color) {
            style.color = item.color;
          }
          if (item.colorMode !== 'DEFAULT' && item.backgroundColor) {
            style.backgroundColor = item.backgroundColor;
          }

          return (
            <span
              key={item.id}
              className={classNames('badge user-select-none', {
                'bg-info':
                  item.colorMode === 'DEFAULT' &&
                  item.backgroundColorMode === 'DEFAULT',
                'rounded-pill': item.roundedPill,
              })}
              style={style}
            >
              {item.name}
            </span>
          );
        })}
    </>
  );
};

const Style = ({
  icons,
  classes,
  styles,
}: {
  icons: string[];
  classes: string[];
  styles: {};
}) => {
  return (
    <>
      {icons.map((value) => {
        return (
          <i
            className={classNames('bi', `bi-${value}`, classes)}
            style={styles}
            key={value}
          ></i>
        );
      })}
    </>
  );
};

const Name = ({
  id,
  name,
  classes,
  styles,
  isEdit,
  isLink,
  contentLink,
  textDecorationNone,
}: {
  id: number;
  name: string;
  classes: string[];
  styles: {};
  isEdit?: boolean;
  isLink?: boolean;
  contentLink?: string;
  textDecorationNone?: boolean;
}) => {
  const postViewMutation = useMutation(async (variables: TBody<void>) => {
    await postView(variables);
  });

  function onClickLink() {
    postViewMutation.mutateAsync({
      id,
    });
  }

  if (isEdit) {
    return (
      <Link
        className="link-body-emphasis link-offset-3 link-underline-opacity-0 link-underline-opacity-100-hover"
        href={`/posts/${id}/edit`}
      >
        <span className={classNames(classes)} style={styles}>
          {name}
        </span>
        <i className="bi bi-pencil-square text-secondary ms-2"></i>
      </Link>
    );
  }

  return (
    <>
      {isLink ? (
        <Link
          onClick={onClickLink}
          href={contentLink!}
          className="link-body-emphasis link-offset-3 link-underline-opacity-0 link-underline-opacity-100-hover"
          rel="noopener noreferrer"
          target="_blank"
        >
          <span className={classNames(classes)} style={styles}>
            {name}
          </span>
          <i className="bi bi-box-arrow-up-right ms-2"></i>
        </Link>
      ) : (
        <Link
          className={classNames(
            'link-body-emphasis',
            textDecorationNone
              ? 'text-decoration-none cursor-default'
              : 'link-offset-3 link-underline-opacity-0 link-underline-opacity-100-hover',
          )}
          href={`/posts/${id}`}
        >
          <span className={classNames(classes)} style={styles}>
            {name}
          </span>
        </Link>
      )}
    </>
  );
};
